package com.xhwl.centiotdata.service.integrateconfig;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xhwl.centiotdata.service.cent.IDeviceCentService;
import com.xhwl.centiotdata.utils.UploadUtils;
import com.xhwl.common.query.cent.device.IntegrationConfigQuery;
import com.xhwl.common.query.cent.device.ProductAccessQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author： lianghz
 * @Description：
 * @Date 2021/12/17/ 11:57
 */
@Component
public class IntegrationConfigHandler implements ApplicationRunner, ApplicationEventPublisherAware {

    @Autowired
    private IDeviceCentService deviceCentService;

    private ApplicationEventPublisher applicationEventPublisher;

    @Override
    public void run(ApplicationArguments args) throws Exception {

        //初始化时，开启可以访问非安全图片
        UploadUtils.slovePKIX();

        this.executeUpdate();
    }

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
    }

    public void executeUpdate() {
        try {
            // 数据变更
            IntegrationConfig.integrationConfigList = deviceCentService.listProductAccess(null, new ProductAccessQuery());
            IntegrationConfigEvent event = new IntegrationConfigEvent(this);

            try {
                event.setDeviceProjectSupplierCategories(deviceCentService.onListingDeviceSupplierCategoryVO(
                        new Page(1, Integer.MAX_VALUE),
                        new IntegrationConfigQuery())
                );
            } catch (Exception e) {
                // 查询集成配置失败
            }

            // 通知变更
            applicationEventPublisher.publishEvent(event);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
